package qldoanra.sosanhtyle;

import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import dbutil.ConnectDB;
import utils.DateUtils;
import utils.UtilsOnScopes;

public class BeanSSTyLe {
	private String error;
	private java.util.Date starDate;
	private java.util.Date endDate;
	private String bieudo ="";
	private String nationTo1;
	private String nationTo2;
	private boolean tableData;
	private String bieumau="/qldoanra/sosanhtyle/emptyBieuMau.xhtml";
	private List<TableDisplay> list; 
	/***************************************************************************
	 * Method name : checkValue 
	 * Return type : boolean Decription :Kiem tra du
	 * lieu dau vao Created date : Jun 22, 2008 Author : Honglk
	 **************************************************************************/
	public boolean checkValue(java.util.Date star, java.util.Date end) {
		boolean result = true;
		if (star == null || star.equals("")) {
			this.setError("Bạn chưa chọn ngày bắt đầu !");
			return result = false;
		} else if (end == null || end.equals("")) {
			this.setError("Bạn chưa chọn ngày kết thúc !");
			return result = false;
		} else if (star.compareTo(end) > 0) {
			this.setError("Ngày kết thúc lớn hơn ngày bắt đầu !");
			return result = false;

		}
		return result;
	}

	/***************************************************************************
	 * Method name : reset 
	 * Return type : String 
	 * Decription :reset data Created
	 * date : Jul 22, 2008 Author : Honglk
	 **************************************************************************/
	public String reset() {
		UtilsOnScopes.getSession().removeAttribute("beanSSTyLe");
		return "okSSTyLe";
	}

	/***************************************************************************
	 * Method name : total 
	 * Return type : int Decription :tinh tong so luong
	 * nguoi di den tat ca cac nuoc 
	 * Created date : Jul 22, 2008 Author : Honglk
	 **************************************************************************/
	public float total() {
		float total = 0;
		String temp = this.filtData();
		String SQL = "SELECT COUNT(*) AS count FROM doanra D "
				+ " INNER JOIN dsnguoidi B ON D.madoan = B.iddoanra"
				+ " WHERE B.trangthaidi = '1' "
				+" AND D.flagdelete = 0 "
				+ temp;
		System.out.println(SQL);
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		try {
			if (array.size() > 0) {
				HashMap<String, Object> hash = new HashMap<String, Object>();
				hash = (HashMap<String, Object>) array.get(0);
				total = Float.parseFloat(hash.get("count").toString());
			}
			ConnectDB.connect.close();
		} catch (Exception e) {

		}
		return total;
	}

	/***************************************************************************
	 * Method name : total 
	 * Return type : int Decription :tinh tong so luong
	 * nguoi di den 1 nuoc nao do 
	 * Created date : Jul 22, 2008 
	 * Author : Honglk
	 **************************************************************************/
	public float totalToNation(String nationTo) {
		float total = 0f;
		String temp = this.filtData();
		String SQL = "SELECT COUNT(*) AS count FROM doanra D "
				+ " INNER JOIN dsnguoidi B ON D.madoan = B.iddoanra"
				+ " WHERE B.trangthaidi = '1' AND D.nuocden LIKE '" + nationTo
				+ "' "
				+ " AND D.flagdelete = 0 "
				+ temp;
		System.out.println(SQL);
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		try {
			if (array.size() > 0) {
				HashMap<String, Object> hash = new HashMap<String, Object>();
				hash = (HashMap<String, Object>) array.get(0);
				total = Float.parseFloat(hash.get("count").toString());
			}
			ConnectDB.connect.close();
		} catch (Exception e) {

		}
		return total;
	}

	/**************************************
	 * Method name		: tyLePhanTram
	 * Return type		: String
	 * Decription		:tinh ty le phan tram
	 * Created date		: Jul 23, 2008
	 * Author			: Honglk
	 **************************************/
	public String tyLePhanTram(String nationTo) {
		String result = "";
		double total = this.total();
		double totalItem = this.totalToNation(nationTo);
		double tyLe = 0.0;
		try{
		 tyLe = (totalItem / total) * 100;
		}catch(Exception e){
			tyLe = 0.0;
		}
		result = utils.FormatStyle.numberFormat(tyLe) + "%";
		return result;
	}
	/**************************************
	 * Method name		: tyLePhanTramDouble
	 * Return type		: double
	 * Decription		:tinh ty le phan tram tra ve kieu double
	 * Created date		: Jul 23, 2008
	 * Author			: Honglk
	 **************************************/
	public double tyLePhanTramDouble(String nationTo) {
		double total = this.total();
		double totalItem = this.totalToNation(nationTo);
		double tyLe = 0.0;
		try{
			tyLe = (totalItem / total) * 100;
		}catch(Exception e){
			tyLe = 0.0;
		}
		return tyLe;
	}
	/**************************************
	 * Method name		: tyLePhanTramRemain
	 * Return type		: String
	 * Decription		:Tra ve ty le phan tram con lai
	 * Created date		: Jul 23, 2008
	 * Author			: Honglk
	 **************************************/
	public String tyLePhanTramRemain(String nationTo1,String nationTo2) {
		String result = "";
		double totalItem1 = this.tyLePhanTramDouble(nationTo1);
		double totalItem2 = this.tyLePhanTramDouble(nationTo2);
		double tyLe = 0.0;
		try{
			tyLe = 100.0 - (totalItem1 +totalItem2);
		}catch(Exception e){
			tyLe = 100.0;
		}
		result = utils.FormatStyle.numberFormat(tyLe) + "%";
		System.out.println("ty le phan tram:"+tyLe);
		return result;
	}
	

	/***************************************************************************
	 * Method name : filtData Return type :
	 *  String Decription : Created date :
	 * Jul 22, 2008 
	 * Author : Honglk
	 **************************************************************************/
	private String filtData() {
		String result = "";
		if (this.starDate != null && this.endDate != null) {
			Date starDateSQL = DateUtils.utilDateToSqlDate(this.getStarDate());
			Date endDateSQL = DateUtils.utilDateToSqlDate(this.getEndDate());
			result = " AND D.ngaydi BETWEEN '" + starDateSQL + "' AND '"
					+ endDateSQL + "'";
		}
		return result;
	}

	/***************************************************************************
	 * Method name : view Return type :
	 * String Decription :xem ty le phan tram
	 * Created date : Jul 22, 2008 
	 * Author : Honglk
	 **************************************************************************/
	public String view() {
		this.setError("");
		if (this.checkValue(this.starDate, this.endDate) == false) {
			return "";
		} else if (this.nationTo1 == null || this.nationTo1.equals("-1")) {
			this.setError("Bạn chưa nhập <b>'nước đến 1'</b> !");
			return "";
		} else if (this.nationTo2 == null || this.nationTo2.equals("-1")) {
			this.setError("Bạn chưa nhập <b>'nước đến 2'</b> !");
			return "";
		}else if(this.nationTo1.equals(this.nationTo2)){
			this.setError("<b> 'Nước đến 1' </b> và <b> 'nước đến 2' </b> không đuợc trùng nhau ! !");
			return "";
		}
		this.createImage();
		this.setBieudo("image/bieudo.gif");
		if(this.tableData == true){
			this.tables();
			if(this.list.size() > 0){
			this.setBieumau("/qldoanra/sosanhtyle/bieumau.xhtml");
			}else{
				this.setBieumau("/qldoanra/sosanhtyle/emptyBieuMau.xhtml");
			}
		}else{
			this.setBieumau("/qldoanra/sosanhtyle/emptyBieuMau.xhtml");
		}
		return "okSSTyLe";
	}
	
	public String tables(){
		List<TableDisplay> list = new ArrayList<TableDisplay>();
//		int stt = 0;
//		for (int i = 0; i < 2; i++) {
//			stt = i + 1;
//		TableDisplay table = new TableDisplay();
//		table.setStt(String.valueOf(stt));
//		table.setQuocgia(this);
		TableDisplay table1 = new TableDisplay();
		table1.setStt("1");
		table1.setQuocgia(this.nationTo1);
		table1.setSoluongnguoidi(String.valueOf(this.totalToNation(this.nationTo1)));
		table1.setTylephantram(this.tyLePhanTram(this.nationTo1));
		
		TableDisplay table2 = new TableDisplay();
		table2.setStt("2");
		table2.setQuocgia(this.nationTo2);
		table2.setSoluongnguoidi(String.valueOf(this.totalToNation(this.nationTo2)));
		table2.setTylephantram(this.tyLePhanTram(this.nationTo2));
		
		list.add(table1);
		list.add(table2);
		
		this.setList(list);
		return "";
	}

	/**************************************
	 * Method name		: delete
	 * Return type		: void
	 * Description		:xoa file hinh cu
	 * Created date		: Jul 27, 2008
	 * Author			: Honglk
	 **************************************/
	public void delete(){
		String realPath = UtilsOnScopes.getSession().getServletContext().getRealPath("qldoanra/sosanhtyle/image/");
		File file = new File(realPath + "/bieudo.gif");
		file.delete();
	}
	/***************************************************************************
	 * Method name : createImage Return type : void Decription :Dua ra bieu do
	 * Created date : Jul 22, 2008 Author : Honglk
	 **************************************************************************/
	public void createImage() {
		this.delete();
		DefaultPieDataset data = new DefaultPieDataset();
		String key1 = this.nationTo1 + "(" + 
		this.tyLePhanTram(this.nationTo1)
				+ ")";
		float value1 = this.totalToNation(this.nationTo1);
		String key2 = this.nationTo2 + "(" + 
		this.tyLePhanTram(this.nationTo2)
				+ ")";
		float value2 = this.totalToNation(this.nationTo2);
		String key3 = "Còn lại" + "(" + 
		this.tyLePhanTramRemain(this.nationTo1, this.nationTo2)
		+ ")";
		float value3 = this.total()-(this.totalToNation(this.nationTo1) + this.totalToNation(this.nationTo2));
		data.setValue(key1, value1);
		data.setValue(key2, value2);
		data.setValue(key3, value3);
		JFreeChart chart = ChartFactory.createPieChart("TY LE PHAN TRAM", data,
				true, // legend?
				true, // tooltips?
				false // URLs?
				);
		try {
			BufferedImage image = chart.createBufferedImage(495, 400);
			String realPath = UtilsOnScopes.getSession().getServletContext().getRealPath("qldoanra/sosanhtyle/image/");
			File file = new File(realPath + "/bieudo.gif");
			ImageIO.write(image, "gif", file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**************************************
	 * Method name		: getError
	 * Return type		: String
	 * Description		:
	 * Created date		: Aug 12, 2008
	 * Author			: Honglk
	 **************************************/
	
	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public java.util.Date getStarDate() {
		return starDate;
	}

	public void setStarDate(java.util.Date starDate) {
		this.starDate = starDate;
	}

	public java.util.Date getEndDate() {
		return endDate;
	}

	public void setEndDate(java.util.Date endDate) {
		this.endDate = endDate;
	}

	public String getBieudo() {
		return bieudo;
	}

	public void setBieudo(String bieudo) {
		this.bieudo = bieudo;
	}

	public String getNationTo1() {
		return nationTo1;
	}

	public void setNationTo1(String nationTo1) {
		this.nationTo1 = nationTo1;
	}

	public String getNationTo2() {
		return nationTo2;
	}

	public void setNationTo2(String nationTo2) {
		this.nationTo2 = nationTo2;
	}
	
	public boolean isTableData() {
		return tableData;
	}

	public void setTableData(boolean tableData) {
		this.tableData = tableData;
	}

	public String getBieumau() {
		return bieumau;
	}

	public void setBieumau(String bieumau) {
		this.bieumau = bieumau;
	}

	public List<TableDisplay> getList() {
		return list;
	}

	public void setList(List<TableDisplay> list) {
		this.list = list;
	}

	public static void main(String[] args) {
		BeanSSTyLe ss = new BeanSSTyLe();
		System.out.println(ss.tyLePhanTram(""));
	}
	
}
